package com.xingfei.blog.redisCluster;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;

/**
 * 具体redis操作
 * Created by yhang on 2017/6/1.
 * http://www.cnblogs.com/java-zhao/p/5347703.html
 */
@Component
public class RedisClusterUtil {

    private final static Logger logger = LoggerFactory.getLogger(RedisClusterUtil.class);

    @Autowired
    private JedisCluster jedisCluster;

    public String get(String key) {
        //重置keys生存时间
        Long ttl = jedisCluster.ttl(key);
        if (ttl > 0 && ttl < (60 * 30)) {
            jedisCluster.expire(key, (60 * 30));
        }
        return jedisCluster.get(key);
    }

    public void set(String key, String value, int seconds) {
        logger.info("生成redis key:"+key);
        if (seconds == 0) {
            jedisCluster.set(key, value);
        } else {
            //指定key过期时间
            jedisCluster.setex(key, seconds, value);
        }
    }

    public void del(String key) {
        Long del = jedisCluster.del(key);
    }

    public boolean isExisit(String key) {
        return jedisCluster.exists(key);
    }

    /**
     * 根据key将值加1
     * @param key
     * @return
     */
    public Long incr(String key){
        return jedisCluster.incr(key);
    }
}
